package aishua.com.mytestapplist;

import android.accounts.Account;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListPopupWindow;
import android.widget.Toast;

import org.w3c.dom.Document;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import aishua.com.mytestapplist.mgr.FileMgr;
import aishua.com.mytestapplist.utils.LogUtils;

/**
 * Created by aishua on 2017/7/5.
 */

public class AutoFillActivity extends Activity {
    private WebView mWebView;
    private boolean SHOW_DEBUG = true;
    private ProgressDialog mProgressDialog = null;
    private static String mJsFile;
    private ListPopupWindow mPopupWindow = null;
    private ImageButton mFillBtn;
    private ArrayAdapter adapter;

    //    京东测试地址
//    private String location = "http://ui.ptlogin2.qq.com/cgi-bin/login?appid=46000101&style=8&lang=&low_login=1&hide_title_bar=1&hide_close_icon=1&daid=6&hln_css=http://mat1.gtimg.com/www/mb/images/logo244x100.png&s_url=http%3A%2F%2Fw.t.qq.com%2Ftouch";
    private String location = "https://www.baidu.com/";
//    String location= "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F%3Fjumpfrom%3Dweibocom";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);
        mWebView = (WebView) findViewById(R.id.mWebView);
        mFillBtn = (ImageButton) findViewById(R.id.fill_btn);
        mPopupWindow = new ListPopupWindow(this);
        mPopupWindow.setWidth((int) getResources().getDimension(R.dimen.autologin_popup_width));
        mPopupWindow.setVerticalOffset((int) getResources().getDimension(R.dimen.autologin_vertical_offset));
        mPopupWindow.setModal(true);
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(AutoFillActivity.this,"position-->"+position,Toast.LENGTH_LONG).show();
                fillLogin(mWebView);
                mPopupWindow.dismiss();
            }
        });

        configureSettings(mWebView.getSettings());
        try {
            setJsFile();
            mWebView.setWebChromeClient(new WebChromeClient() {
                public boolean onConsoleMessage(ConsoleMessage cm) {
                    showMsg(cm.message() + " -- From line " + cm.lineNumber());
                    return true;
                }
            });
            mWebView.setWebViewClient(new WebViewClient() {
                private boolean pageLoaded = false;

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Toast.makeText(AutoFillActivity.this, "Error during page loading: " + description, Toast.LENGTH_LONG).show();
                }

                public void onPageStarted(WebView view, String url, Bitmap favicon) {

                    if (!isFinishing()) {
                        if (mProgressDialog == null) {
                            mProgressDialog = new ProgressDialog(AutoFillActivity.this);
                            mProgressDialog.setMessage(AutoFillActivity.this.getString(R.string.WaitLoadingMsg));
                            mProgressDialog.setIndeterminate(true);
                            mProgressDialog.setCancelable(true);
                            mProgressDialog.show();
                        }

                    }
                }

                public void onPageFinished(WebView view, String url) {

                    if (!(this.pageLoaded)) {
                        Toast.makeText(AutoFillActivity.this, "loading with json:", Toast.LENGTH_LONG).show();
                        fillLogin(view);
                    }
                    pageLoaded = true;
                    mProgressDialog.dismiss();
                }

                public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                }

                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                }

                public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                }

                public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
                }

                public void onLoadResource(WebView view, String url) {
                }
            });

            loadUrl(location);
            adapter=new ArrayAdapter<String>(AutoFillActivity.this,android.R.layout.simple_list_item_single_choice,getsource());
        } catch (Exception e) {

//            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(location)));
            Toast.makeText(AutoFillActivity.this, "自动填充失败" + e.getMessage(), Toast.LENGTH_LONG).show();

        }

    }

    @SuppressLint({"SetJavaScriptEnabled"})
    private void configureSettings(WebSettings settings) {
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setSupportMultipleWindows(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setBlockNetworkImage(false);
        settings.setLightTouchEnabled(true);
    }

    private void setJsFile() throws Exception {
        if (TextUtils.isEmpty(mJsFile)) {
            mJsFile = FileMgr.inputStreamToString(getAssets().open("js/getLogin.js"));
        }
    }

    private void showMsg(String msg) {
        if (SHOW_DEBUG) {
            Log.v("WEBDEBUG", msg);
        }
    }

    public void fillLogin(WebView webView) {

        try {
//            GenericItem item;
//            if (itemBase.getVaultB5() == null) {
//                item = getRecordMgr().getItem(itemBase.mUuId);
//            } else {
//                item = getRecordMgrB5().getItem(itemBase.mUuId, itemBase.getVaultB5());
//            }
//            WebForm webForm = (WebForm) item;
//            webForm.fillProperties();
            fillLogin(webView, "{secureContents：{Username:hpuwfq@163.com,Password:wfq.010203}}".toString());
        } catch (Exception e) {

            Toast.makeText(AutoFillActivity.this, "自动填充失败" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public void fillLogin(WebView webView, String webForm) {
        try {
            String js ="javascript:" + mJsFile;
//            String js = mJsFile.replace("$OBJECT_JSON", webForm.replace("$ACTION", "'fillLogin'"));
//            String js = mJsFile.replace("%u%", "541246469").replace("%p%", "wfq.010203");
            String aPassword = "wfq.010203".replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"");
            String aUserName = "hpuwfq@163.com".replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"");
            String escapePassword = URLEncoder.encode(aPassword, "UTF-8");
            js = String.format(js, new Object[]{aUserName, escapePassword, Boolean.valueOf(true)});


            LogUtils.v("js----->"+js);
            if (Build.VERSION.SDK_INT >= 19) {
                webView.evaluateJavascript(js, null);
            } else {
                webView.loadUrl(js);
            }
        } catch (Exception e) {

            Toast.makeText(AutoFillActivity.this, "自动填充失败" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    public void loadUrl(String url) {

        Uri uri = uriFromUrl(url);
        if (uri != null) {
            this.mWebView.loadUrl(uri.toString());
        }
    }

    public static Uri uriFromUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        Uri uri = Uri.parse(url);
        if (TextUtils.isEmpty(uri.getScheme())) {
            return Uri.parse("http://" + url);
        }
        return uri;
    }

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.mPopupWindow.isShowing()) {
            this.mPopupWindow.dismiss();
            new Handler().postDelayed(new Runnable() {
                public void run() {

                    showLogins(mFillBtn);
                }
            }, 250);

        }
    }

    public void showLogins(View view) {

        showLogins(view, true);
    }

    public void showLogins(View view, boolean fetchRichIcons) {

//        ListAdapter adapter;
//        List<GenericItemBase> items = null;
        String domainName = null;
        if (!TextUtils.isEmpty(this.mWebView.getUrl())) {
//            items = getAllLogins();
            String host = Uri.parse(this.mWebView.getUrl()).getHost();
            Pattern p = Pattern.compile("([\\w\\d]*\\.)?(.*\\..*)");
            if (!(host == null || p == null)) {
                Matcher m = p.matcher(host);
                if (m.find()) {
                    domainName = m.group(2);
                    LogUtils.v("showLogins---->"+domainName);
                }
            }
        }
//        List<GenericItemBase> logins = new ArrayList();
//        if (!(items == null || items.isEmpty() || TextUtils.isEmpty(domainName))) {
//            for (GenericItemBase item : items) {
//                if (item.mLocation != null && item.mLocation.contains(domainName)) {
//                    logins.add(item);
//                }
//            }
//        }
//
//            if (fetchRichIcons) {
//                ActivityHelper.loadRowImageBitmaps(RichIconCache.getInstance(this), logins, this);
//            }
//            adapter = new ItemListAdapter(logins, this);
//            ((ItemListAdapter) adapter).setShowQaButton(false);

        this.mPopupWindow.setAdapter(adapter);
        this.mPopupWindow.setAnchorView(view);
        this.mPopupWindow.show();
    }

//    private List<GenericItemBase> getAllLogins() {
//        List<GenericItemBase> allLogins = new ArrayList();
//        List<GenericItemBase> logins = getRecordMgr().getItemsForType(1);
//        if (logins != null) {
//            allLogins.addAll(logins);
//        }
//        if (AccountsCollection.hasAccounts()) {
//            for (Account account : AccountsCollection.getAccounts()) {
//                for (VaultB5 vault : account.getVaults()) {
//                    try {
//                        logins = getRecordMgrB5().getItemsForType(1, vault);
//                        if (logins != null) {
//                            allLogins.addAll(logins);
//                        }
//                    } catch (AppInternalError e) {
//                        ActivityHelper.showToast((Context) this, e.getMessage());
//                    }
//                }
//            }
//        }
//        Collections.sort(allLogins);
//        return allLogins;
//    }
//


    public List<String> getsource(){
        List<String> list=new ArrayList<String>();
        for(int i=0;i<3;i++)
        {
            list.add("欢迎您,"+i);
        }
        return list;
    }
//
//    public GenericItem fillProperties() throws JSONException {
//        super.fillProperties();
//        boolean extendedFieldsAdded = false;
//        boolean extendedFieldsDriverAdded = false;
//        createFreshPropertiesList();
//        for (ItemProperty prop : this.mPropertiesList) {
//            String propKey = prop.getKey();
//            if (!TextUtils.isEmpty(prop.getKey()) && propKey.equals("location")) {
//                prop.setValue(this.mLocation);
//            } else if (prop.isReadOnly()) {
//                extendedFieldsAdded = true;
//            }
//        }
//        if (!TextUtils.isEmpty(this.mSecureContent)) {
//            JSONObject secureContentJSon = new JSONObject(this.mSecureContent);
//            this.autologinJsonString = new JSONObject().put("secureContents", secureContentJSon).toString();
//            if (secureContentJSon.has("fields")) {
//                JSONArray fieldsArr = secureContentJSon.getJSONArray("fields");
//                if (fieldsArr != null && fieldsArr.length() > 0) {
//                    for (int i = 0; i < fieldsArr.length(); i++) {
//                        String propertyName;
//                        String propertyValue;
//                        JSONObject fieldObj = (JSONObject) fieldsArr.get(i);
//                        if (fieldObj.has("name") && fieldObj.has("value")) {
//                            propertyName = fieldObj.getString("name");
//                            propertyValue = fieldObj.getString("value");
//                            if (TextUtils.isEmpty(propertyValue)) {
//                            }
//                        } else {
//                            if (fieldObj.has("designation") && fieldObj.has("value")) {
//                                propertyName = fieldObj.getString("designation");
//                                propertyValue = fieldObj.getString("value");
//                            }
//                        }
//                        if (fieldObj.has("designation")) {
//                            for (ItemProperty property : this.mPropertiesList) {
//                                String propertyKey = property.getKey();
//                                if (!TextUtils.isEmpty(propertyKey)) {
//                                    if (propertyKey.equalsIgnoreCase(fieldObj.getString("designation"))) {
//                                        property.setValue(propertyValue);
//                                    }
//                                    if (propertyKey.equalsIgnoreCase(RFC2617Digest.USERNAME)) {
//                                        this.mSubtitle = property.getValue();
//                                    }
//                                }
//                            }
//                        } else if (!(extendedFieldsAdded || TextUtils.isEmpty(propertyName))) {
//                            if (!extendedFieldsDriverAdded) {
//                                this.mPropertiesList.add(new ItemProperty(ItemPropertyType.WEBFORM_EXTENED_FLD_DRIVER));
//                                extendedFieldsDriverAdded = true;
//                            }
//                            this.mPropertiesList.add(new ItemProperty(propertyName, propertyName, propertyValue).setReadOnly());
//                        }
//                    }
//                }
//            }
//            ItemProperty lastPropertyInList = (ItemProperty) this.mPropertiesList.get(this.mPropertiesList.size() - 1);
//            if (lastPropertyInList.getType() != ItemPropertyType.COMMENT) {
//                if (secureContentJSon.has("notesPlain")) {
//                    boolean commentPropFound = false;
//                    for (ItemProperty prop2 : this.mPropertiesList) {
//                        if (prop2.getType() == ItemPropertyType.COMMENT) {
//                            prop2.setValue(secureContentJSon.getString("notesPlain"));
//                            commentPropFound = true;
//                            break;
//                        }
//                    }
//                    if (!commentPropFound) {
//                        ItemProperty notesProperty = new ItemProperty("notesPlain", R.string.lbl_Attachment, ItemPropertyType.COMMENT);
//                        notesProperty.setValue(secureContentJSon.getString("notesPlain"));
//                        this.mPropertiesList.add(notesProperty);
//                    }
//                }
//            } else if (secureContentJSon.has("notesPlain")) {
//                lastPropertyInList.setValue(secureContentJSon.getString("notesPlain"));
//            }
//        }
//        return this;
//    }
//
//
//    protected List<ItemProperty> createFreshPropertiesList() {
//        boolean addNoteSectionToEnd = false;
//        if (this.mPropertiesList == null || this.mPropertiesList.isEmpty()) {
//            this.mPropertiesList = super.createFreshPropertiesList();
//        } else if (!this.mPropertiesList.isEmpty()) {
//            List<ItemProperty> freshPropertyList = new ArrayList();
//            addNoteSectionToEnd = true;
//            for (ItemProperty prop : this.mPropertiesList) {
//                String propKey = prop.getKey();
//                if ((!TextUtils.isEmpty(prop.getKey()) && !propKey.equals("location") && !propKey.equals("password") && !propKey.equals(RFC2617Digest.USERNAME)) || prop.getType() == ItemPropertyType.WEBFORM_EXTENED_FLD_DRIVER) {
//                    if (prop.getType() == ItemPropertyType.COMMENT) {
//                        addNoteSectionToEnd = false;
//                    }
//                    freshPropertyList.add(prop);
//                }
//            }
//            this.mPropertiesList = freshPropertyList;
//        }
//        this.mPropertiesList.add(0, new ItemProperty(RFC2617Digest.USERNAME, R.string.lbl_UserName));
//        this.mPropertiesList.add(1, new ItemProperty("password", (int) R.string.lbl_Pwd, ItemPropertyType.PWD));
//        this.mPropertiesList.add(2, new ItemProperty("location", (int) R.string.lbl_Url, ItemPropertyType.LINK));
//        if (addNoteSectionToEnd) {
//            this.mPropertiesList.add(this.mPropertiesList.size(), new ItemProperty("notesPlain", (int) R.string.lbl_Attachment, ItemPropertyType.COMMENT));
//        }
//        return this.mPropertiesList;
//    }

}
